using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;
using MediPlatform.ErrorCode;
using MediPlatform.Write.Api.Models;
using BCrypt.Net;

namespace MediPlatform.Write.Api.Controllers
{
    /// <summary>
    /// 用户写入控制器
    /// </summary>
    [ApiController]
    [Route("api/write/[controller]")]
    // 移除授权要求
    // [Authorize]
    public class UserWriteController : ControllerBase
    {
        private readonly IBaseRepository<User> _userRepository;
        private readonly ILogger<UserWriteController> _logger;

        public UserWriteController(IBaseRepository<User> userRepository, ILogger<UserWriteController> logger)
        {
            _userRepository = userRepository;
            _logger = logger;
        }

        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="request">用户创建请求</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        // 移除角色授权
        // [Authorize(Roles = "admin")]
        public async Task<ApiResult<UserInfo>> CreateUser([FromBody] RegisterRequest request)
        {
            try
            {
                _logger.LogInformation("开始创建用户: {Username}", request.Username);

                // 检查用户名是否已存在
                var existingUser = await _userRepository.GetAsync(u => u.Username == request.Username);
                if (existingUser != null)
                {
                    return ApiResult<UserInfo>.Error("用户名已存在");
                }



                // 检查邮箱是否已存在
                if (!string.IsNullOrEmpty(request.Email))
                {
                    var existingEmail = await _userRepository.GetAsync(u => u.Email == request.Email);
                    if (existingEmail != null)
                    {
                        return ApiResult<UserInfo>.Error("邮箱已被使用");
                    }
                }

                // 创建新用户
                var user = new User
                {
                    UserId = $"U{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}",
                    Username = request.Username,
                    Email = request.Email,
                    PhoneNumber = request.PhoneNumber,
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password),
                    Role = request.Role ?? "patient",
                    CreatedAt = DateTime.Now,
                    UpdatedAt = DateTime.Now
                };

                await _userRepository.AddAsync(user);
                await _userRepository.SaveChangesAsync();

                _logger.LogInformation("用户创建成功: {UserId}", user.UserId);

                var userInfo = new UserInfo
                {
                    UserId = user.UserId,
                    Username = user.Username,
                    Email = user.Email,
                    PhoneNumber = user.PhoneNumber,
                    Role = user.Role
                };

                return ApiResult<UserInfo>.Success(userInfo, "用户创建成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建用户失败: {Username}", request.Username);
                return ApiResult<UserInfo>.Error("创建用户失败");
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{userId}")]
        public async Task<ApiResult<UserInfo>> UpdateUser(string userId, [FromBody] UpdateUserRequest request)
        {
            try
            {
                _logger.LogInformation("开始更新用户: {UserId}", userId);

                var user = await _userRepository.GetAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return ApiResult<UserInfo>.Error("用户不存在");
                }

                // 写服务不需要权限检查
                // var currentUserId = User.FindFirst("UserId")?.Value;
                // var currentUserRole = User.FindFirst("role")?.Value;
                // 
                // if (currentUserRole != "admin" && currentUserId != userId)
                // {
                //     return ApiResult<UserInfo>.Error("无权限更新此用户信息");
                // }

                // 更新用户信息
                if (!string.IsNullOrEmpty(request.Username) && request.Username != user.Username)
                {
                    var existingUser = await _userRepository.GetAsync(u => u.Username == request.Username);
                    if (existingUser != null)
                    {
                        return ApiResult<UserInfo>.Error("用户名已存在");
                    }
                    user.Username = request.Username;
                }

                if (!string.IsNullOrEmpty(request.Email) && request.Email != user.Email)
                {
                    var existingEmail = await _userRepository.GetAsync(u => u.Email == request.Email);
                    if (existingEmail != null)
                    {
                        return ApiResult<UserInfo>.Error("邮箱已被使用");
                    }
                    user.Email = request.Email;
                }

                if (!string.IsNullOrEmpty(request.PhoneNumber) && request.PhoneNumber != user.PhoneNumber)
                {
                    var existingPhone = await _userRepository.GetAsync(u => u.PhoneNumber == request.PhoneNumber);
                    if (existingPhone != null)
                    {
                        return ApiResult<UserInfo>.Error("手机号已被使用");
                    }
                    user.PhoneNumber = request.PhoneNumber;
                }

                if (!string.IsNullOrEmpty(request.Password))
                {
                    user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
                }

                // 写服务不需要权限检查，允许更改角色
                if (!string.IsNullOrEmpty(request.Role))
                {
                    user.Role = request.Role;
                }

                user.UpdatedAt = DateTime.Now;

                _userRepository.Update(user);
                await _userRepository.SaveChangesAsync();

                _logger.LogInformation("用户更新成功: {UserId}", userId);

                var userInfo = new UserInfo
                {
                    UserId = user.UserId,
                    Username = user.Username,
                    Email = user.Email,
                    PhoneNumber = user.PhoneNumber,
                    Role = user.Role
                };

                return ApiResult<UserInfo>.Success(userInfo, "用户信息更新成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新用户失败: {UserId}", userId);
                return ApiResult<UserInfo>.Error("更新用户失败");
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{userId}")]
        // 移除角色授权
        // [Authorize(Roles = "admin")]
        public async Task<ApiResult<bool>> DeleteUser(string userId)
        {
            try
            {
                _logger.LogInformation("开始删除用户: {UserId}", userId);

                var user = await _userRepository.GetAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return ApiResult<bool>.Error("用户不存在");
                }

                // 防止删除管理员用户
                if (user.Role == "admin")
                {
                    return ApiResult<bool>.Error("不能删除管理员用户");
                }

                _userRepository.Delete(user);
                await _userRepository.SaveChangesAsync();

                _logger.LogInformation("用户删除成功: {UserId}", userId);

                return ApiResult<bool>.Success(true, "用户删除成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户失败: {UserId}", userId);
                return ApiResult<bool>.Error("删除用户失败");
            }
        }
    }

    /// <summary>
    /// 用户更新请求模型
    /// </summary>
    public class UpdateUserRequest
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string? Username { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string? Email { get; set; }

        /// <summary>
        /// 手机号
        /// </summary>
        public string? PhoneNumber { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string? Password { get; set; }

        /// <summary>
        /// 角色
        /// </summary>
        public string? Role { get; set; }
    }
} 